import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainBox from '../views/MainBox.vue'
import routesConfig from './config'

// import {useStore} from "vuex"
// const store = useStore();

import store from "../store/index.js"
const routes = [
  {
    path:"/login",
    name:"login",
    component:Login
  },
  {
    path:"/mainbox",
    name:"mainbox",
    component:MainBox
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 每次路由跳转之前都会进来
router.beforeEach((to,from,next) => {
  if(to.name == "login") {
    next();
  }else {
    // 如果已经授权
    // 未授权重定向到login
    if(!localStorage.getItem("token")) {
      next({
        path:"/login"
      })
    }else {
      if(!store.state.isGetterRouter) {
        router.removeRoute('mainbox')
        configRouter();
        next({
          path:to.fullPath
        });
      }
      next();
    }
  }
})
const configRouter = () => {
  if(!router.hasRoute("mainbox")) {
    router.addRoute({
      path:"/mainbox",
      name:"mainbox",
      component:MainBox
    })
  }
  routesConfig.forEach((item) => {
    if(item.manage) {
      // console.log('进入',item.name);
      // console.log('flag',store.state.userInfo.role == 1);
      (store.state.userInfo.role == 1) && router.addRoute("mainbox",item)
    }else {
      router.addRoute("mainbox",item);
    }
   // router.addRoute("mainbox",item);
  })

  store.commit("changeGetterRouter",true);
}

export default router
